<template>
  <div class="cart">
    <div class="number" v-if="!iswait">
      <div class="n-left">
        购物数量<span>{{ cart.cartList.length }}</span>
      </div>
      <div class="n-right" @click="delt" v-if="!del">管理</div>
      <div class="n-right" @click="delt" v-if="del">取消</div>
    </div>
    <div class="content" v-if="!iswait">
      <ul v-if="cart.cartList.length > 0">
        <li class="item" v-for="(item,index) in cart.cartList" v-bind:key="index">
          <div class="i-left">
            <div
              class="left-box"
              :class="{ active: !item.check }"
              @click="check(item)"
            >
              <span class="iconfont icon-duigou" v-if="item.check"></span>
            </div>
          </div>
          <div class="i-middle">
            <router-link :to="{path : '/home/detail',query :{id : item.storeInfo.id}}">
            <img :src="item.storeInfo.image" alt="" />
            </router-link>
          </div>
          <div class="i-right">
            <router-link :to="{path : '/home/detail',query :{id : item.storeInfo.id}}">
            <div class="title">
              {{ item.storeInfo.store_name }}
            </div>
            </router-link>
            <div class="r-bottom">
              <div class="price">¥{{ item.storeInfo.price }}</div>
              <div class="goods-number">
                <div class="goods-sub" @click="sub(item)">-</div>
                <div class="goods-n">{{ item.num }}</div>
                <div class="goods-add" @click="add(item)">+</div>
              </div>
            </div>
          </div>
        </li>
      </ul>
      <nodata v-if="cart.cartList.length == 0"></nodata>
    </div>
    <div class="bottom" v-if="!iswait">
      <div class="b-left">
        <div class="checkbox" @click="checkAll" :class="{ active: !checkA }">
            <span class="iconfont icon-duigou" v-if="checkA"></span>
        </div>
        <div class="checkall">
          全选 (<span>{{ totalNum }}</span
          >)
        </div>
      </div>
      <div class="b-right">
        <div class="b-price">¥{{price}}</div>
        <div class="buy" :class="{dele : hasCheck}">
          <div>
            <router-link to="address"><div class="aaa" v-if="!del">立即下单</div></router-link>
            <div class="aaa" v-if="del" @click="deleteCheck">删除商品</div>
          </div>
        </div>
      </div>
    </div>
    <wait v-if="iswait"></wait>
  </div>
</template>
<script>
import { get } from "@/utils/http";
import { mapState } from "vuex";
import nodata from '@/components/nodata';
import wait from '@/components/wait';
export default {
  data() {
    return {
      cartList: [
        {
          src: "http://47.115.51.185//uploads/attach/2021/06/20210626/2fa49a708c9ce750007a1c43f07d2aaf.jpg",
          check: false,
          title: "中国风棉麻t恤男装中式短袖麻料盘扣中袖上衣大码亚麻T恤夏季宽松",
          price: 0.09,
          num: 4,
          id: 0,
        },
        {
          src: "http://47.115.51.185//uploads/attach/2021/06/20210626/2fa49a708c9ce750007a1c43f07d2aaf.jpg",
          check: false,
          title: "中国风棉麻t恤男装中式短袖麻料盘扣中袖上衣大码亚麻T恤夏季宽松",
          price: 0.09,
          num: 4,
          id: 1,
        },
        {
          src: "http://47.115.51.185//uploads/attach/2021/06/20210626/2fa49a708c9ce750007a1c43f07d2aaf.jpg",
          check: false,
          title: "中国风棉麻t恤男装中式短袖麻料盘扣中袖上衣大码亚麻T恤夏季宽松",
          price: 0.09,
          num: 4,
          id: 2,
        },
      ],
      del: false,
      totalNum: 0,
      checkA: false,
      price : "0.00",
      hasCheck:false,
      dataList : [],
      iswait : true,
    };
  },
  methods: {
    check(item) {
      item.check = !item.check;
      this.totalNum = 0;
      let isAll = true;
      let ischeck = false;
      this.$store.state.cart.cartList.forEach((element) => {
        if (element.check == true) {
          this.totalNum++;
          ischeck = true;
        }else{
            isAll = false;
        }
      });
      if(isAll){
          this.checkA = false;
          this.checkAll();
      }else{
          this.checkA = false;
      }
      this.hasCheck = ischeck; 
      this.priceAll();
    },
    checkAll() {
      if(this.dataList.length == 0){
        return;
      }
      this.checkA = !this.checkA;
      this.hasCheck = this.checkA;
      if (this.checkA) {
        this.$store.state.cart.cartList.forEach((element) => {
          element.check = true;
        });
        this.totalNum = this.$store.state.cart.cartList.length;
      }else{
          this.$store.state.cart.cartList.forEach((element) => {
          element.check = false;
        });
        this.totalNum = 0;
      }
      this.priceAll();
    },
    priceAll(){
        this.price = 0;
        this.$store.state.cart.cartList.forEach((element) => {
          if(element.check == true){
              this.price += element.storeInfo.price * element.num;
          }
        });
        this.price = this.price.toFixed(2);
    },
    delt() {
      this.del = !this.del;
    },
    sub(item){
        item.num--;
        if(item.num<=1){item.num = 1};
        this.priceAll();
    },
    add(item){
        item.num++;
        if(item.num>=99){item.num = 99};
        this.priceAll();
    },
    getData(id,arr){
      get(`/api/product/detail/${id}`)
        .then((response) => {
          let res = response.data;
          if (res.status == 200) {
            this.dataList.push(res.data);
            // let arr = this.$store.state.cart.cartList;
           // arr.push(this.$route.query.id);
            // arr = [...new Set(arr)];
            this.dataList.forEach((element,i) => {
                // console.log(i,element);
                element.check = false;
                element.num = 1;
            });
            // console.log(this.dataList)
          this.$store.dispatch("cart/setcartAsync",this.dataList);
          if(this.dataList.length == arr.length){
              this.iswait = false;
          }
          }
      })
    },
    deleteCheck(){
      if(this.hasCheck == false){
        alert('请选择商品');
        return;
      }
      let newarr = [];
        this.$store.state.cart.cartList.forEach((element,index) => {
          if(element.check == true){
          // console.log(index,element.storeInfo.id);
          // console.log(this.dataList)
          }else{
            newarr.push(element);
          }
        });
      this.dataList = newarr;
      this.$store.dispatch("cart/setcartAsync",this.dataList);
      let str = '';
      this.$store.state.cart.cartList.forEach((element,index) => {
          str += element.storeInfo.id + ',';
        });
      str = str.substring(0, str.lastIndexOf(','));  
      // console.log(str);
      localStorage.setItem('cartId',str);
      this.price = 0;
      this.totalNum = 0;
      if(this.dataList.length == 0){
        this.checkA = false;
      }
    },
    init(){
      let str = localStorage.getItem('cartId');
      // console.log(str);
      if(str != null){
          if(str[0] == ','){ 
            str = str.slice(1);  
          };
          let arr = str.split(',');
          // console.log(arr);
          // arr =  [...new Set(arr)];
          arr.forEach((element,index,arr) => {
            if(element != ''){
                this.getData(element,arr);
            }
          });
      }else{
        this.iswait = false;
      }
    }
  },
  created(){
    this.init();
  },
  computed:{
    ...mapState(["cart"]),
  },
  components:{
    nodata,
    wait,
  },
  beforeRouteLeave(to,from,next){
    // console.log(to);
    // if(to.path == '/address'){
    //   if()
    // }
    if(to.path == '/address'){
      if(this.hasCheck == false){
        alert('请选择商品!');
        return;
      }else{
        next();
      }
    }
    next();
  }
};
</script>
<style lang="less" scoped>
@import "../../assets/font/font_icon2/iconfont.css";
@import "../../assets/less/variable.less";
.cart {
  position: absolute;
  top: 0;
  background: #f5f5f5;
  width: 100%;
  height: 100%;
  .number {
    background: white;
    display: flex;
    padding: 10px 20px;
    box-sizing: border-box;
    justify-content: space-between;
    font-size: 16px;
    > div {
      height: 25px;
      line-height: 25px;
    }
    .n-left {
      span {
        display: inline-block;
        margin-left: 10px;
        color: @color4;
      }
    }
    .n-right {
      padding: 0px 20px;
      box-sizing: border-box;
      border: 1px solid #ccc;
    }
  }
  .content {
    width: 100%;
    padding-bottom: 100px;
    ul {
      width: 100%;
      li.item {
        display: flex;
        background: white;
        margin: 5px 0;
        padding: 10px;
        .i-left {
          flex-basis: 10%;
          width: 10%;
          position: relative;
          .left-box {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translateX(-50%) translateY(-50%);
            width: 20px;
            height: 20px;
            span {
              display: inline-block;
              width: 100%;
              height: 100%;
              color: @color4;
              font-size: 21px;
              line-height: 20px;
              text-align: center;
            }
          }
          .left-box.active {
            border-radius: 50%;
            border: 1px solid #ccc;
          }
        }
        .i-middle {
          flex-basis: 25%;
          width: 25%;
          margin: 0 10px;
          img {
            width: 100%;
          }
        }
        .i-right {
          flex-basis: 65%;
          width: 65%;
          position: relative;
          box-sizing: border-box;
          .title {
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            font-size: 16px;
          }
          .r-bottom {
            width: 100%;
            position: absolute;
            bottom: 5px;
            display: flex;
            justify-content: space-between;
            .goods-number {
              display: flex;
              > div {
                height: 20px;
                line-height: 20px;
                text-align: center;
                width: 30px;
                border: 1px solid #ccc;
              }
              .goods-sub {
                border-right: 0;
              }
              .goods-add {
                border-left: 0;
              }
            }
          }
        }
      }
    }
  }
  .bottom {
    position: fixed;
    bottom: @footerHeight;
    width: 100%;
    display: flex;
    justify-content: space-between;
    background: white;
    border-top: 1px solid #ccc;
    border-bottom: 1px solid #ccc;
    font-size: 16px;
    height: 50px;
    line-height: 50px;
    padding: 10px;
    box-sizing: border-box;
    .b-left {
      display: flex;
      align-items: center;
      .checkbox {
        width: 20px;
        height: 20px;
        margin-right: 10px;
        position: relative;
        span{
            position: absolute;
            top: 0;
            right: 0;
            display: inline-block;
            width: 100%;
            height: 100%;
            color: #EE8972;
            font-size: 0.56rem;
            line-height: 0.53333rem;
            text-align: center;
        }
      }
      .checkbox.active{
        border-radius: 50%;
        border: 1px solid #ccc;
        box-sizing: border-box;
      }
      .checkall {
        font-size: 16px;
      }
    }
    .b-right {
      display: flex;
      align-items: center;
      .buy {
        margin: 0 10px;
        border-radius: 20px;
        background: @color4;
        width: 100px;
        text-align: center;
        div{
            color: white;
        }
        .aaa {
          height: 40px;
          line-height: 40px;
        }
      }
      .buy.dele{
          background: red;
      }
      .b-price {
        color: @color4;
      }
    }
  }
}
</style>